<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>随机点名系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f0f2f5;
            margin: 0;
            padding: 20px;
            min-height: 100vh;
        }

        .container {
            width: 80%;
            max-width: 1200px;
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        }

        h1 {
            color: #1890ff;
            text-align: center;
            margin-bottom: 30px;
            font-size: 2.5em;
        }

        .button-group {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-bottom: 30px;
        }

        button {
            padding: 12px 24px;
            font-size: 1.2em;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .primary-button {
            background-color: #1890ff;
            color: white;
        }

        .secondary-button {
            background-color: #52c41a;
            color: white;
        }

        .danger-button {
            background-color: #ff4d4f;
            color: white;
        }

        button:hover {
            opacity: 0.8;
            transform: translateY(-2px);
        }

        #result {
            font-size: 2em;
            text-align: center;
            margin: 30px 0;
            padding: 20px;
            border-radius: 5px;
            background-color: #e6f7ff;
            color: #1890ff;
            min-height: 60px;
        }

        .student-list {
            margin-top: 30px;
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            padding: 20px;
            background-color: #fafafa;
            border-radius: 5px;
        }

        .student-item {
            padding: 10px;
            background-color: white;
            border-radius: 5px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        @media (max-width: 768px) {
            .container {
                width: 95%;
                padding: 15px;
            }

            button {
                padding: 10px 20px;
                font-size: 1em;
            }

            #result {
                font-size: 1.5em;
            }
        }

        .settings-panel {
            margin: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .call-count {
            margin: 10px 0;
            color: #666;
        }
        
        .student-stats {
            margin: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .student-stats table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .student-stats th, .student-stats td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>随机点名系统</h1>
        <div class="button-group">
            <button class="primary-button" onclick="randomCall()">开始点名</button>
            <button class="secondary-button" onclick="resetStudents()">重置名单</button>
            <button class="danger-button" onclick="showRemainingStudents()">查看剩余学生</button>
        </div>
        <div id="result"></div>
        <div id="studentList" class="student-list"></div>
    </div>

    <!-- 添加设置面板 -->
    <div class="settings-panel">
        <h3>点名设置</h3>
        <div>
            <label for="maxCallTimes">默认最大点名次数：</label>
            <input type="number" id="maxCallTimes" min="1" value="1">
            <button onclick="setMaxCallTimes()">保存设置</button>
        </div>
        <div style="margin-top: 15px;">
            <h4>设置个人点名次数</h4>
            <div>
                <label for="studentName">学生姓名：</label>
                <input type="text" id="studentName">
                <label for="studentMaxTimes">最大点名次数：</label>
                <input type="number" id="studentMaxTimes" min="1" value="1">
                <button onclick="setStudentMaxCallTimes()">保存设置</button>
            </div>
        </div>
    </div>
    
    <!-- 添加统计信息面板 -->
    <div class="student-stats">
        <h3>点名统计</h3>
        <table>
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>小组</th>
                    <th>已点次数</th>
                    <th>最大次数</th>
                </tr>
            </thead>
            <tbody id="statsTableBody">
            </tbody>
        </table>
    </div>

    <script>
        function randomCall() {
            fetch('/api/random-call')
                .then(response => response.text())
                .then(data => {
                    document.getElementById('result').innerText = data;
                });
        }

        function resetStudents() {
            fetch('/api/reload-students', {
                method: 'POST'
            })
            .then(response => response.text())
            .then(() => {
                document.getElementById('result').innerText = '名单已重置';
                showRemainingStudents();
            });
        }

        function showRemainingStudents() {
            fetch('/api/remaining-students')
                .then(response => response.json())
                .then(data => {
                    const studentList = document.getElementById('studentList');
                    studentList.innerHTML = '';
                    
                    // 按小组分类
                    const groupedStudents = {};
                    for (const [student, group] of Object.entries(data)) {
                        if (!groupedStudents[group]) {
                            groupedStudents[group] = [];
                        }
                        groupedStudents[group].push(student);
                    }

                    // 按小组显示学生
                    for (const [group, students] of Object.entries(groupedStudents)) {
                        const groupDiv = document.createElement('div');
                        groupDiv.className = 'student-group';
                        groupDiv.innerHTML = `<h3>${group}</h3>`;
                        
                        students.forEach(student => {
                            const studentDiv = document.createElement('div');
                            studentDiv.className = 'student-item';
                            studentDiv.innerText = student;
                            groupDiv.appendChild(studentDiv);
                        });
                        
                        studentList.appendChild(groupDiv);
                    }
                });
        }

        // 页面加载时显示学生列表
        window.onload = showRemainingStudents;

        // 页面加载时获取当前设置
        window.onload = async function() {
            await loadCurrentSettings();
            await updateStats();
        }
        
        // 加载当前设置
        async function loadCurrentSettings() {
            try {
                const response = await fetch('/api/get-max-call-times');
                const maxTimes = await response.json();
                document.getElementById('maxCallTimes').value = maxTimes;
            } catch (error) {
                console.error('获取设置失败:', error);
            }
        }
        
        // 设置最大点名次数
        async function setMaxCallTimes() {
            const times = document.getElementById('maxCallTimes').value;
            try {
                await fetch('/api/set-max-call-times?times=' + times, {
                    method: 'POST'
                });
                alert('设置已保存');
            } catch (error) {
                console.error('保存设置失败:', error);
                alert('保存设置失败');
            }
        }
        
        // 设置学生个人最大点名次数
        async function setStudentMaxCallTimes() {
            const studentName = document.getElementById('studentName').value;
            const times = document.getElementById('studentMaxTimes').value;
            
            if (!studentName) {
                alert('请输入学生姓名');
                return;
            }
            
            try {
                const response = await fetch(`/api/set-student-max-call-times?studentName=${encodeURIComponent(studentName)}&times=${times}`, {
                    method: 'POST'
                });
                const result = await response.text();
                alert(result);
                if (result.includes('成功')) {
                    await updateStats();
                }
            } catch (error) {
                console.error('设置失败:', error);
                alert('设置失败，请重试');
            }
        }
        
        // 更新统计信息
        async function updateStats() {
            try {
                const [studentsResponse, countResponse] = await Promise.all([
                    fetch('/api/remaining-students'),
                    fetch('/api/student-call-count')
                ]);
                
                const students = await studentsResponse.json();
                const callCounts = await countResponse.json();
                
                const tableBody = document.getElementById('statsTableBody');
                tableBody.innerHTML = '';
                
                for (const [name, group] of Object.entries(students)) {
                    const maxTimesResponse = await fetch(`/api/get-student-max-call-times?studentName=${encodeURIComponent(name)}`);
                    const maxTimes = await maxTimesResponse.json();
                    
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${name}</td>
                        <td>${group}</td>
                        <td>${callCounts[name] || 0}</td>
                        <td>${maxTimes}</td>
                    `;
                    tableBody.appendChild(row);
                }
            } catch (error) {
                console.error('更新统计信息失败:', error);
            }
        }
        
        // 修改原有的randomCall函数，添加更新统计信息的调用
        async function randomCall() {
            try {
                const response = await fetch('/api/random-call');
                const result = await response.text();
                document.getElementById('result').innerText = result;
                
                // 更新统计信息
                await updateStats();
            } catch (error) {
                console.error('点名失败:', error);
                document.getElementById('result').innerText = '点名失败，请重试';
            }
        }
        
        // 修改原有的reloadStudents函数，添加更新统计信息的调用
        async function reloadStudents() {
            try {
                await fetch('/api/reload-students', {
                    method: 'POST'
                });
                document.getElementById('result').innerText = '已重置所有学生数据';
                
                // 更新统计信息
                await updateStats();
            } catch (error) {
                console.error('重置失败:', error);
                document.getElementById('result').innerText = '重置失败，请重试';
            }
        }
    </script>
</body>
</html>